#!/bin/bash

DEFAULT_THRESHOLD_PERCENT=90
DEFAULT_MAX_CHECK_PEROID=10

help() {
  echo "Usage:"
  echo "  zmachine mem monitor"
  echo ""
  echo "Options:"
  echo "  -e, --exec <COMMAND>  Run command in threshold percent"
  echo "  -t, --threshold       Threshold, unit: percent (0 - 100), default: 90"
}

core() {
  local command=""
  local threshold_percent=$DEFAULT_THRESHOLD_PERCENT

  while [[ $# -gt 0 ]]; do
    local key=$1
    local value=$2

    # echo "key: $key, value: $value"
    case $key in
      -h | --help)
        help
        exit 0
        ;;
      -e | --exec)
        command=$value
        shift # past key
        shift # past value

        # @TODO zmachine mem monitor --exec "zmachine ip" -t 90
        local maybe_part_of_command=$1
        while true; do
          # if not start with -, it is a part of command
          echo $maybe_part_of_command | grep "^-" >> /dev/null 2>&1
          if [ "$?" = "0" ]; then
            break
          fi

          # echo "$maybe_part_of_command ..."
          shift
          command="${command} ${maybe_part_of_command}"
          maybe_part_of_command=$1
        done
        ;;
      -t | --threshold)
        threshold_percent=$value
        shift # past key
        shift # past value
        ;;
      *)
        echo "ERROR: unknown parameter \"$key\""
        help
        exit 1
        ;;
    esac
  done

  while true; do
    local usage=$(zmachine mem usage)
    if [ $usage -gt $threshold_percent ]; then
      log::info "[$(timestamp)] memory usage(${usage}%) reached threshold percent($kill_percent%), run: ${command}"
      eval $command
      
      # 执行完任务要即使休息，接着干容易疲劳
      sleep 5
    else
      echo "[$(timestamp)] memory usage: $usage%"
    fi

    local period=$((DEFAULT_MAX_CHECK_PEROID - $usage / $DEFAULT_MAX_CHECK_PEROID))
    if [ $period -lt 1 ]; then
      period=1
    fi

    sleep $period
  done
}

run() {
  core $@
}

run $@
